const parse = require('url').parse

module.exports = (obj) => {
  return (req, res, next) => {
    if (!obj[req.method]) {
      next()
      return
    }
    const routes = obj[req.method]
    const url = parse(req.url)

    for (const path in routes) {
      const fn = routes[path]
      const regStr = path
        .replace(/\//g, '\\/')
        .replace(/:(\w+)/g, '([^\\/]+)')

      const reg = new RegExp('^' + regStr + '$')

      const captures = url.pathname.match(reg)

      if (captures) {
        const args = [req, res].concat(captures.slice(1))
        fn.apply(null, args)
        return
      }
    }

    next()
  }
}
